package com.hdu.service;


import com.alibaba.fastjson.JSONObject;
import com.hdu.config.DelayTaskClientProperties;
import com.hdu.result.R;
import com.hdu.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.IOException;

import static com.alibaba.fastjson.JSON.parseObject;
import static java.util.Objects.isNull;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static com.hdu.util.ParamChecker.unValidParam;


@Slf4j
public class TaskService {

    private final DelayTaskClientProperties delayTaskClientProperties;

    private final static String ADD_TASK_SUFFIX = "/task/add";
    private final static String DELETE_TASK_SUFFIX = "/task/delete";

    public TaskService(DelayTaskClientProperties delayTaskClientProperties) {
        this.delayTaskClientProperties = delayTaskClientProperties;
    }

    public boolean addTask(String taskName, int priority, Object taskParam, long executeTime) {
        return addOrDelete(null, taskName, priority, taskParam, executeTime, true);
    }

    public boolean deleteTask(Long id, String taskName, int priority, long executeTime) {
        return addOrDelete(id, taskName, priority, null, executeTime, false);
    }

    private boolean addOrDelete(Long id, String taskName, int priority, Object taskParam, long executeTime, boolean add) {
        unValidParam(
                (add && isEmpty(taskName))
                        || (add && priority < 0)
                        || (add && isNull(taskParam))
                        || (add && executeTime <= System.currentTimeMillis())
                        || (!add && id == null),
                "参数不合法"
        );
        val postBody = new JSONObject();
        if (add) {
            postBody.put("taskName", taskName);
            postBody.put("priority", priority);
            postBody.put("executeTime", executeTime);
            postBody.put("taskParam", taskParam);
        } else {
            // delete

        }

        val url = delayTaskClientProperties.getDelayTaskCenterUrl() + (add ? ADD_TASK_SUFFIX : DELETE_TASK_SUFFIX);
        try {
            val res = HttpUtils.doPost(
                    url,
                    postBody.toJSONString()
            );
            val r = parseObject(res, R.class);
            return r.getCode() == 200;
        } catch (IOException e) {
            log.error("{} error, taskName : {}, priority : {}, taskParam : {}, executeTime : {}",
                    add ? "addTask" : "deleteTask", taskName, priority, taskParam, executeTime, e);
            return false;
        }
    }
}
